package edu.scau.mis.web.controller.pos;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeRefundResponse;

import edu.scau.mis.pos.domain.Alipayment;
import edu.scau.mis.pos.service.IAlipaymentService;
import edu.scau.mis.web.config.AlipayConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RequestMapping("/alipay")
@RestController
public class AlipayController {
    /**
     * 沙箱支付配置
     */
    @Resource
    private AlipayConfig alipayConfig;

    /**
     * 沙箱支付代理
     */
    @Resource
    private DefaultAlipayClient defaultAlipayClient;

    /**
     * 支付成功通知地址
     * todo: 确保更改为最新域名
     */
    private static final String NOTIFY_PATH = "http://dmdifj.natappfree.cc" + "/alipay/notify";

    @Resource
    private IAlipaymentService alipaymentService;



    /**
     * 支付
     *
     * @param orderNo   交易单号
     * @param amount    商品名称
     * @return
     */
    @GetMapping("/pay")
    //orderNo是该订单的orderNo，amount是应付金额,name是商品名字
    public String alipay(String orderNo, Double amount , String name) {
        // 封装支付请求体
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        // json请求体
        JSONObject bizContent = new JSONObject();
        // 交易单号-这里传入订单的order_no
        bizContent.put("out_trade_no", orderNo);
        // 商品名称
        bizContent.put("subject", name);
        // 交易金额-这里传入的是应付的金额，需要前端给数据
        bizContent.put("total_amount", amount);
        // 沙箱支付环境唯一配置
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");
        // 设置支付宝通知地址
        request.setNotifyUrl(NOTIFY_PATH);
        request.setBizContent(bizContent.toString());
        // 支付
        String formPage;
        try {
            formPage = defaultAlipayClient.pageExecute(request).getBody();
        } catch (AlipayApiException e) {
            throw new RuntimeException("订单支付异常：" + orderNo, e);
        }
        // 渲染页面
        return formPage;
    }

    /**
     * 支付成功通知接口
     *
     * @param request
     */
    @PostMapping("/notify")
    public void notify(HttpServletRequest request) throws AlipayApiException {
        // 除了以下三个参数外，还有其他参数，可自行debug查看
        //交易状态
        String tradeStatus = request.getParameter("trade_status");
        //这里是我们传入的orderNo
        String tradeNo = request.getParameter("out_trade_no");
        //支付宝交易凭证号
        String alipayNo = request.getParameter("trade_no");
        //应付的交易金额
        Double total_amount = Double.valueOf(request.getParameter("total_amount"));
        //买家实际支付金额
        Double amount = Double.valueOf(request.getParameter("buyer_pay_amount"));

        System.out.println("交易状态：" + tradeStatus);
        System.out.println("订单No：" + tradeNo);
        System.out.println("支付宝交易凭证号：" + alipayNo);
        System.out.println("应付总金额：" + total_amount);
        System.out.println("用户实际支付金额" + amount);
//        alipaymentController.add(alipayment);


        if (!"TRADE_SUCCESS".equals(tradeStatus)) {
            System.out.println("订单支付失败：" + tradeNo);
        }
        // 验签
        Map<String, String> params = new HashMap<>();
        for (String name : request.getParameterMap().keySet()) {
            params.put(name, request.getParameter(name));
        }
        String content = AlipaySignature.getSignCheckContentV1(params);
        String alipayPublicKey = alipayConfig.getAlipayPublicKey();
        String sign = request.getParameter("sign");
        boolean check = AlipaySignature.rsa256CheckContent(content, sign, alipayPublicKey, AlipayConfig.CHARSET);
        if (!check) {
            System.out.println("订单验签异常：" + tradeNo);
        }
        // 验签成功后，保存订单...
        System.out.println("订单支付成功：" + tradeNo);
        Alipayment alipayment = new Alipayment();
        alipayment.setAlipayNo(alipayNo);
        alipayment.setAmount(amount);
        alipayment.setTotalAmount(total_amount);
        alipayment.setTradeStatus(tradeStatus);
        alipayment.setOrderNo(Long.parseLong(tradeNo));
        alipayment.setCreateTime(new Date());

        alipaymentService.insert(alipayment);
    }
}